package com.wzcx.orclib;

import static com.wzcx.orclib.MaskView.MASK_TYPE_NONE;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.wzcx.util.DimensionUtil;

public class MaskViewLayout extends RelativeLayout implements IMaskView {


  public MaskViewLayout(Context context) {
    this(context, null);
  }

  public MaskViewLayout(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public MaskViewLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    setWillNotDraw(false);

    cardNo.setColor(Color.WHITE);
    cardNo.setStyle(Style.STROKE);
    cardNo.setStrokeWidth(DimensionUtil.dpToPx(1.5f));

    LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    lp.addRule(CENTER_HORIZONTAL);
    tvCardTitle = new TextView(context);
    tvCardTitle.setTextSize(16);
    tvCardTitle.setTextColor(Color.WHITE);
    tvCardTitle.setShadowLayer(DimensionUtil.dpToPx(4), 0, DimensionUtil.dpToPx(1),
        Color.parseColor("#33000000"));

    addView(tvCardTitle, lp);

    lp = new LayoutParams(LayoutParams.WRAP_CONTENT,
        DimensionUtil.dpToPx(25));

    lp.addRule(CENTER_HORIZONTAL);
    hintViewText = new TextView(getContext());
    hintViewText.setBackgroundResource(R.drawable.bd_ocr_round_corner);
    hintViewText.setAlpha(0.5f);
    hintViewText.setPadding(DimensionUtil.dpToPx(10), 0, DimensionUtil.dpToPx(10), 0);

    hintViewText.setGravity(Gravity.CENTER);
    hintViewText.setTextColor(Color.WHITE);
    hintViewText.setTextSize(12);

    addView(hintViewText, lp);



    getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
      @Override
      public void onGlobalLayout() {


        if (frame.top > 0 && frame.bottom > 0) {

          MarginLayoutParams layoutParams = (MarginLayoutParams) tvCardTitle.getLayoutParams();

          layoutParams.topMargin = frame.top + DimensionUtil.dpToPx(16);
          tvCardTitle.setLayoutParams(layoutParams);

          layoutParams = (MarginLayoutParams) hintViewText.getLayoutParams();

          layoutParams.topMargin = frame.bottom + DimensionUtil.dpToPx(16);
          hintViewText.setLayoutParams(layoutParams);

          getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
      }
    });

  }


  private int maskType = 0;

  private int maskColor = Color.argb(100, 0, 0, 0);

  private Paint eraser = new Paint(Paint.ANTI_ALIAS_FLAG);
  private Paint pen = new Paint(Paint.ANTI_ALIAS_FLAG);
  private Paint cardNo = new Paint(Paint.ANTI_ALIAS_FLAG);

  private Rect frame = new Rect();

  private Rect rectCardNo = new Rect();

  private MaskConfig maskConfig;


  /**
   * 提示证件标题
   */
  private TextView tvCardTitle;


  /**
   * 用于显示提示证 "请对齐身份证正面" 之类的文字
   */
  private TextView hintViewText;


  @Override
  protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    if (w > 0 && h > 0) {
      float ratio = h > w ? 0.9f : 0.72f;

      int width = (int) (w * ratio);
      int height = width * 400 / 620;

      int left = (w - width) / 2;
      int top = (h - height) / 2;
      int right = width + left;
      int bottom = height + top;

      frame.left = left;
      frame.top = top;
      frame.right = right;
      frame.bottom = bottom;

      if (maskConfig != null && maskConfig.width >0 && maskConfig.height > 0) {

        if (maskConfig.gravity == Gravity.LEFT) {

          left +=  maskConfig.leftMargin >0?maskConfig.leftMargin:DimensionUtil.dpToPx(18);

          bottom -= maskConfig.bottomMargin>0?maskConfig.bottomMargin:DimensionUtil.dpToPx(30);


          rectCardNo.set(left, bottom - maskConfig.height, left + maskConfig.width, bottom);
        } else if (maskConfig.gravity == Gravity.RIGHT) {

          right -=  maskConfig.rightMargin >0?maskConfig.rightMargin:DimensionUtil.dpToPx(18);
          bottom -= maskConfig.bottomMargin>0?maskConfig.bottomMargin:DimensionUtil.dpToPx(30);

          rectCardNo.set(right - maskConfig.width, bottom - maskConfig.height, right, bottom);

        }

      }else {
        rectCardNo.setEmpty();
      }


    }
  }


  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    int width = frame.width();
    int height = frame.height();

    int left = frame.left;
    int top = frame.top;
    int right = frame.right;
    int bottom = frame.bottom;

    canvas.drawColor(maskColor);
    fillRectRound(left, top, right, bottom, 30, 30, false);

    canvas.drawPath(path, pen);
    canvas.drawPath(path, eraser);

    if (!rectCardNo.isEmpty()){

      canvas.drawRect(rectCardNo, cardNo);
    }

  }

  private Path path = new Path();

  private Path fillRectRound(float left, float top, float right, float bottom, float rx, float ry,
      boolean
          conformToOriginalPost) {

    path.reset();
    if (rx < 0) {
      rx = 0;
    }
    if (ry < 0) {
      ry = 0;
    }
    float width = right - left;
    float height = bottom - top;
    if (rx > width / 2) {
      rx = width / 2;
    }
    if (ry > height / 2) {
      ry = height / 2;
    }
    float widthMinusCorners = (width - (2 * rx));
    float heightMinusCorners = (height - (2 * ry));

    path.moveTo(right, top + ry);
    path.rQuadTo(0, -ry, -rx, -ry);
    path.rLineTo(-widthMinusCorners, 0);
    path.rQuadTo(-rx, 0, -rx, ry);
    path.rLineTo(0, heightMinusCorners);

    if (conformToOriginalPost) {
      path.rLineTo(0, ry);
      path.rLineTo(width, 0);
      path.rLineTo(0, -ry);
    } else {
      path.rQuadTo(0, ry, rx, ry);
      path.rLineTo(widthMinusCorners, 0);
      path.rQuadTo(rx, 0, rx, -ry);
    }

    path.rLineTo(0, -heightMinusCorners);
    path.close();
    return path;
  }

  {
    // 硬件加速不支持，图层混合。
    setLayerType(View.LAYER_TYPE_SOFTWARE, null);

    pen.setColor(Color.WHITE);
    pen.setStyle(Paint.Style.STROKE);
    pen.setStrokeWidth(6);

    eraser.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
  }

  @Override
  public View getView() {
    return this;
  }

  @Override
  public void setMaskType(int maskType, MaskConfig config) {
    this.maskType = maskType;
    if (config != null) {
      maskConfig = config;

      if (TextUtils.isEmpty(maskConfig.cardTitle)){
        tvCardTitle.setVisibility(GONE);
      }else {
        tvCardTitle.setText(maskConfig.cardTitle);
      }

      if (TextUtils.isEmpty(maskConfig.cardHint)){
        hintViewText.setVisibility(GONE);
      }else {
        hintViewText.setText(maskConfig.cardHint);
      }




    }


  }


  @Override
  public int getMaskType() {
    return maskType;
  }

  @Override
  public Rect getFrameRectExtend() {
    Rect rc = new Rect(frame);
    int widthExtend = (int) ((frame.right - frame.left) * 0.02f);
    int heightExtend = (int) ((frame.bottom - frame.top) * 0.02f);
    rc.left -= widthExtend;
    rc.right += widthExtend;
    rc.top -= heightExtend;
    rc.bottom += heightExtend;
    return rc;
  }

  @Override
  public Rect getFrameRect() {
    if (maskType == MASK_TYPE_NONE){
      return new Rect(0, 0, getWidth(), getHeight());
    }
    return new Rect(frame);
  }
}
